/* Copyright (c) 2022 渝州大数据实验室
 *
 * Lanius is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *
 *     http://license.coscl.org.cn/MulanPSL2
 *
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package org.yzbdl.lanius.orchestrate.interceptor;

import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

import java.util.HashSet;
import java.util.Set;

/**
 * 特殊字符拦截器
 * 废弃（不再使用）
 * @author chenjunhao
 * @date 2022-05-12 09:26
 */
public class SpecialCharacterInterceptor implements InnerInterceptor {

	private static final String LIKE_KEY = "like";
	private static final String QUESTION_KEY = "?";

	@Override
	public void beforeQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {
		String sql = boundSql.getSql().toLowerCase();
		if(!sql.contains(LIKE_KEY)||!sql.contains(QUESTION_KEY)){
			return;
		}
		//切割ew的参数
		String[] strList = sql.split("\\?");
		Set<String> keyNames = new HashSet<>();
		for(int i = 0;i<strList.length;i++){
			if(strList[i].contains(LIKE_KEY)){
				if(boundSql.getParameterMappings().size()>i){
					String keyName = boundSql.getParameterMappings().get(i).getProperty();
					keyNames.add(keyName);
				}
			}
		}
		MetaObject metaObject = ms.getConfiguration().newMetaObject(parameter);
		for(String keyName : keyNames){
			Object value = metaObject.getValue(keyName);
			if(value instanceof String){
				String valStr = value.toString();
				/*
				 * 目前只用到了业务层条件构造查询
				 */
				if(keyName.contains("ew.paramNameValuePairs.")){
					String shortValue = valStr.substring(1,value.toString().length()-1);
					if(isConvert(shortValue)){
						metaObject.setValue(keyName, "%"+convert(shortValue)+"%");
					}
				}else{
					if(isConvert(valStr)){
						metaObject.setValue(keyName, convert(valStr));
					}
				}
			}
		}
	}

	/**
	 * 是否转换
	 * @param str 字符串
	 * @return 布尔值
	 */
	private boolean isConvert(String str){
		return str.contains("\\")||str.contains("_")||str.contains("%");
	}

	/**
	 * 将特殊字符转义
	 * @param str 字符串
	 * @return 转义后的字符
	 */
	private String convert(String str){
		if(StringUtils.isNotBlank(str)){
			str = str.replaceAll("\\\\","\\\\\\\\");
			str = str.replaceAll("_","\\\\_");
			str = str.replaceAll("%","\\\\%");
		}
		return str;
	}

}
